# -*- coding: utf-8 -*-
from datetime import datetime

from typing import Union

import sqlalchemy as sa
from sqlalchemy import ForeignKey, DateTime

from sqlalchemy.orm import Mapped, mapped_column, relationship

from App.common.model import Base, id_key, SoftDeleteMixin
from App.utils.timezone import timezone


class SysUser(Base, SoftDeleteMixin):
    """系统用户表"""

    __tablename__ = 'sys_user'

    id: Mapped[id_key] = mapped_column(init=False)
    username: Mapped[str] = mapped_column(sa.String(20), default='', sort_order=2, comment='用户名')
    nickname: Mapped[str] = mapped_column(sa.String(20), default='', sort_order=3, comment='昵称')
    password: Mapped[str] = mapped_column(sa.String(255), default='', sort_order=4, comment='密码')
    email: Mapped[str] = mapped_column(sa.String(50), default=None, sort_order=5, comment='邮箱')
    is_super: Mapped[int] = mapped_column(sa.INTEGER(), default=0, sort_order=6, comment='超级权限(0否 1是)')
    is_staff: Mapped[int] = mapped_column(sa.INTEGER(), default=1, sort_order=7, comment='后台管理登陆(0否 1是)')
    status: Mapped[int] = mapped_column(sa.INTEGER(), default=1, sort_order=8, comment='用户账号状态(0停用 1正常)')
    is_multi_login: Mapped[int] = mapped_column(sa.INTEGER(), default=0, sort_order=9, comment='是否重复登陆(0否 1是)')
    avatar: Mapped[str | None] = mapped_column(sa.String(255), default=None, sort_order=10, comment='头像')
    phone: Mapped[str | None] = mapped_column(sa.String(11), default=None, sort_order=11, comment='手机号')
    des: Mapped[str | None] = mapped_column(sa.String(255), default=None, sort_order=12, comment='个人介绍')
    last_login_time: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), init=False, comment='上次登录'
    )
    created_time: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), init=False, default_factory=timezone.now, sort_order=999, comment='创建时间'
    )
    updated_time: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), init=False, onupdate=timezone.now, sort_order=999, comment='更新时间'
    )

    role_id: Mapped[int | None] = mapped_column(ForeignKey('sys_role.id', ondelete='SET NULL'), default=None,
                                                sort_order=16, comment='关联角色ID')
    # 用户角色一对一
    role: Mapped[Union['SysRole', None]] = relationship(init=False, back_populates='users')  # noqa: F821
